﻿using LeederGlobal;
using Leeder.Logger;
using LeederWinApp.Business;
using LeederWinApp.Model;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using System.Diagnostics;

namespace LeederWinApp
{
    public partial class FrmMain_Old : UIHeaderAsideMainFrame
    {
        List<UIPage> UIPageList;
        /// <summary>
        /// 系统编号
        /// </summary>
        private int systemId;
        /// <summary>
        /// 日志
        /// </summary>
        public LogOperate LogObj => Log.GetLogger(this.GetType());

        MenuBLL menuBLL = new MenuBLL();

        [Browsable(false)]
        public IFrame Frame
        {
            get; set;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public FrmMain_Old()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 窗体初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMain_Load(object sender, EventArgs e)
        {
            //检查是否有更新
            //checkUpdate();

            //检查是否多开
            string processName = Process.GetCurrentProcess().ProcessName;
            Process[] processes = Process.GetProcessesByName(processName);
            //如果该数组长度大于1，说明多次运行
            if (processes.Length > 1)
            {
                UIMessageBox.ShowError("程序已运行，不能再次打开！");
                Environment.Exit(1);
            }

            SystemConfigurationModel systemConfiguration = new SystemConfigurationModel();
            systemConfiguration.AppName = System.Configuration.ConfigurationManager.AppSettings["app_name"].ToString();
            ApplicationCache.SystemConfiguration = systemConfiguration;
            labelSystemName.Text = ApplicationCache.ProductName;
            labelSystemName.ForeColor = Color.White;
            labelUser.ForeColor = Color.White;

            var loca1 = labelUser.Location;
            loca1.Y = loca1.Y - 10;
            labelUser.Location = loca1;

            var loca2 = labelSystemName.Location;
            loca2.Y = loca2.Y - 15;
            labelSystemName.Location = loca2;

            var loca3 = pictureBox2.Location;
            loca3.Y = loca3.Y - 10;
            pictureBox2.Location = loca3;

            var loca4 = uiAvatar1.Location;
            loca4.Y = loca4.Y - 20;
            uiAvatar1.Location = loca4;

            //从配置文件中获取系统编号
            systemId = int.Parse(System.Configuration.ConfigurationManager.AppSettings["app_key"].ToString());
            //打开软件默认是普通用户权限
            ApplicationCache.CurrentUser = new CurrentUserModel { LoginName = "gtmc", Password = "gtmc", DisplayName = "gtmc", Permission = 2 };
            Menu_Load(systemId);

            /**********************
            //登录方法
            FLogin frm = new FLogin();
            frm.ShowDialog();
            if (frm.IsLogin)
            {
                ApplicationCache.CurrentUser = frm.user;
                Menu_Load(ApplicationCache.CurrentUser.permission.ToString());
                UIMessageTip.ShowOk("登录成功");
            }
            frm.Dispose();
            *****************************************/


            if (ApplicationCache.CurrentUser.Permission == 0)
            {
                labelUser.Text = "管理员(" + ApplicationCache.CurrentUser.DisplayName + ")";
                timer1.Start();
            }
            else if (ApplicationCache.CurrentUser.Permission == 2)
                labelUser.Text = "普通用户(" + ApplicationCache.CurrentUser.DisplayName + ")";

            if (this.WindowState == FormWindowState.Maximized)
            {
                //this.WindowState = FormWindowState.Normal;
            }
            else
            {
                //全屏
                this.ShowFullScreen = true;
                this.WindowState = FormWindowState.Maximized;
            }
        }

        #region 捕捉电脑空闲时间
        [StructLayout(LayoutKind.Sequential)]
        struct LASTINPUTINFO
        {
            //设置结构体块容量
            [MarshalAs(UnmanagedType.U4)]
            public int cbSize;

            //捕获的时间
            [MarshalAs(UnmanagedType.U4)]
            public uint dwTime;
        }

        [DllImport("user32.dll")]
        private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
        /// <summary>
        /// 捕捉电脑没有操作时间（毫秒）
        /// </summary>
        /// <returns></returns>
        private static long GetLastInputTime()
        {
            LASTINPUTINFO vLastInputInfo = new LASTINPUTINFO();
            vLastInputInfo.cbSize = Marshal.SizeOf(vLastInputInfo);
            //捕获时间
            if (!GetLastInputInfo(ref vLastInputInfo)) return 0;
            return Environment.TickCount - (long)vLastInputInfo.dwTime;
        }
        #endregion

        /// <summary>
        /// 根据设定时间内无操作自动降低用户权限
        /// </summary>
        private void InitPermission()
        {
            try
            {
                if (GetLastInputTime() > 60000)
                {
                    this.Invoke(new MethodInvoker(() =>
                      {
                          ApplicationCache.CurrentUser.Permission = 2;
                          labelUser.Text = "普通用户(" + ApplicationCache.CurrentUser.DisplayName + ")";
                          timer1.Stop();
                      }));
                }
            }
            catch (Exception ex)
            {
                LogObj.Error(ex.Message);
            }
        }

        /// <summary>
        /// 菜单加载
        /// </summary>
        /// <param name="systemId">系统编号</param>
        private void Menu_Load(int systemId)
        {
            string strs = "";
            UIPageList = new List<UIPage>();
            //加载前先清空现有菜单
            Aside.ClearAll();
            int pageIndex = 0;
            //根据系统动态加载菜单
            List<MenuModel> MenuList = menuBLL.GetModelAll();
            foreach (MenuModel model in MenuList)
            {
                //调用类库初始化方法,已经初始化则跳过
                if (!strs.Contains(model.AssemblyName))
                {
                    string strClass = model.AssemblyName + ".AppInitializer";
                    string strMethod = "Init";
                    try
                    {
                        Object obj = Assembly.Load(model.AssemblyName).CreateInstance(strClass);   // 获取初始化类的实例
                        Type type = typen(strClass);       // 获取初始化类
                        MethodInfo method = type.GetMethod(strMethod, new Type[] { });      // 获取初始化方法信息
                        object[] parameters = null;                                // 初始化方法参数（空）
                        method.Invoke(obj, parameters);                           // 调用方法，参数
                        strs += model.AssemblyName;                           //记录已初始化的类库，避免重复初始化
                    }
                    catch (Exception ex)
                    {

                    }
                }

                Object frmShow = Assembly.Load(model.AssemblyName).CreateInstance(model.ClassName);
                pageIndex += 1000;
                // Aside创建Controls节点，并给对应的page标号为pageIndex
                // FMain1需要继承UIPage或者 UITitlePage
                // 将Aside和指定的Main对应关联
                UIPage page = AddPage((UIPage)frmShow, pageIndex);
                UIPageList.Add(page);
                page.Name = model.Sn.ToString();
                page.Text = model.MenuName;
                TreeNode treeNode = Aside.CreateNode(page, pageIndex + 10000, pageIndex);
                treeNode.Text = model.MenuName;
                // 需要将修改后的TreeNode重新装入
                Aside.SetNodeItem(treeNode, new NavMenuItem(page));
            }
        }

        /// <summary>
        /// 菜单加载
        /// </summary>
        /// <param name="systemId">系统编号</param>
        private void Menu_Load_NEW(int systemId)
        {
            string path = Application.StartupPath + "\\SubSystem\\";
            string strs = "";
            UIPageList = new List<UIPage>();
            //加载前先清空现有菜单
            Aside.ClearAll();
            int pageIndex = 0;
            //根据系统动态加载菜单
            List<MenuModel> MenuList = menuBLL.GetModelAll();
            foreach (MenuModel model in MenuList)
            {
                //调用类库初始化方法,已经初始化则跳过
                if (!strs.Contains(model.AssemblyName))
                {
                    string strClass = model.AssemblyName + ".AppInitializer";
                    string strMethod = "Init";
                    try
                    {
                        Object obj = Assembly.LoadFile(path + model.AssemblyName + ".dll").CreateInstance(strClass);   // 获取初始化类的实例
                        Type type = typen(strClass);       // 获取初始化类
                        MethodInfo method = type.GetMethod(strMethod, new Type[] { });      // 获取初始化方法信息
                        object[] parameters = null;                                // 初始化方法参数（空）
                        method.Invoke(obj, parameters);                           // 调用方法，参数
                        strs += model.AssemblyName;                           //记录已初始化的类库，避免重复初始化
                    }
                    catch (Exception ex)
                    {

                    }
                }

                Object frmShow = Assembly.LoadFile(path+ model.AssemblyName+".dll").CreateInstance(model.ClassName);

                pageIndex += 1000;
                // Aside创建Controls节点，并给对应的page标号为pageIndex
                // FMain1需要继承UIPage或者 UITitlePage
                // 将Aside和指定的Main对应关联
                UIPage page = AddPage((UIPage)frmShow, pageIndex);
                UIPageList.Add(page);
                page.Name = model.Sn.ToString();
                page.Text = model.MenuName;
                TreeNode treeNode = Aside.CreateNode(page, pageIndex + 10000, pageIndex);
                treeNode.Text = model.MenuName;
                // 需要将修改后的TreeNode重新装入
                Aside.SetNodeItem(treeNode, new NavMenuItem(page));
            }
        }

        /// <summary>
        /// 通过类名获取类型
        /// </summary>
        /// <param name="typeName">类名</param>
        /// <returns></returns>
        private Type typen(string typeName)
        {
            Type type = null;
            Assembly[] assemblyArray = AppDomain.CurrentDomain.GetAssemblies();
            int assemblyArrayLength = assemblyArray.Length;
            for (int i = 0; i < assemblyArrayLength; ++i)
            {
                type = assemblyArray[i].GetType(typeName);
                if (type != null)
                {
                    return type;
                }
            }

            for (int i = 0; (i < assemblyArrayLength); ++i)
            {
                Type[] typeArray = assemblyArray[i].GetTypes();
                int typeArrayLength = typeArray.Length;
                for (int j = 0; j < typeArrayLength; ++j)
                {
                    if (typeArray[j].Name.Equals(typeName))
                    {
                        return typeArray[j];
                    }
                }
            }
            return type;
        }

        #region 登录按钮方法
        private void uiAvatar1_MouseDown(object sender, MouseEventArgs e)
        {
            uiAvatar1.ForeColor = Color.FromArgb(80, 140, 255);
        }

        private void uiAvatar1_MouseHover(object sender, EventArgs e)
        {
            uiAvatar1.FillColor = Color.LightSteelBlue;
        }

        private void uiAvatar1_MouseLeave(object sender, EventArgs e)
        {
            uiAvatar1.FillColor = Color.Silver;
        }

        private void uiAvatar1_MouseUp(object sender, MouseEventArgs e)
        {
            uiAvatar1.ForeColor = Color.FromArgb(80, 160, 255);
            FLogin frm = new FLogin();
            frm.ShowDialog();
            if (frm.IsLogin)
            {
                ApplicationCache.CurrentUser = new CurrentUserModel();
                ApplicationCache.CurrentUser.LoginName = frm.user.LoginName;
                ApplicationCache.CurrentUser.Password = frm.user.Password;
                ApplicationCache.CurrentUser.DisplayName = frm.user.DisplayName;
                ApplicationCache.CurrentUser.Permission = frm.user.Permission;
                //Menu_Load(ApplicationCache.CurrentUser.permission.ToString(),menuId);
                UIMessageTip.ShowOk("登录成功");
            }

            if (ApplicationCache.CurrentUser.Permission == 0)
            {
                labelUser.Text = "管理员(" + ApplicationCache.CurrentUser.DisplayName + ")";
                timer1.Start();
            }
            else if (ApplicationCache.CurrentUser.Permission == 2)
                labelUser.Text = "普通用户(" + ApplicationCache.CurrentUser.DisplayName + ")";
            frm.Dispose();
            //BllBaseAndong bllBaseAndong = new BllBaseAndong();
        }
        #endregion 

        /// <summary>
        /// 退出软件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (UIMessageDialog.ShowMessageDialog("确定要退出系统吗？", UILocalize.AskTitle, true, UIStyle.Red, true, Frame?.TopMost ?? false))
            {
                ShowWaitForm("正在关闭系统，请稍候...");
                //SetWaitFormDescription(UILocalize.SystemProcessing + "50%");
                foreach (UIPage page in UIPageList)
                {
                    page.Close();
                }
                System.Environment.Exit(0);
                HideWaitForm();
            }
            else
            {
                e.Cancel = true;
            }
        }

        /// <summary>
        /// 隐藏左侧菜单栏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Header_DoubleClick(object sender, EventArgs e)
        {
            if (Aside.Width == 159)
                Aside.Width = 0;
            else
                Aside.Width = 159;
        }

        /// <summary>
        /// 帮助
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            UIMessageBox.Show("技术支持电话：13828459051", "帮助", Style, UIMessageBoxButtons.OK, false);
        }

        /// <summary>
        /// 主页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://www.11467.com/qiye/30940002.htm");
        }

        /// <summary>
        /// 检查是否有更新
        /// </summary>
        public void checkUpdate()
        {
            //SoftUpdate app = new SoftUpdate(Application.ExecutablePath, "BlogWriter");
            //app.UpdateFinish += new UpdateState(app_UpdateFinish);
            //try
            //{
            //    if (app.IsUpdate && MessageBox.Show("检查到新版本，是否更新？", "Update", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            //    {
            //
            //        Thread update = new Thread(new ThreadStart(app.Update));
            //        update.Start();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}
        }

        /// <summary>
        /// 更新完成
        /// </summary>
        void app_UpdateFinish()
        {
            MessageBox.Show("更新完成，请重新启动程序！", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 定时任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            InitPermission();
        }
    }
}
